﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace Luka;

/// <summary>
/// 数据规则验证(正则表达式)
/// </summary>
[NotScanned, AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class RuleAttribute : ValidationAttribute
{
    /// <summary>
    /// 正则表达式
    /// </summary>
    public string? Pattern { get; set; }

    /// <summary>
    /// 构造函数
    /// </summary>
    public RuleAttribute()
    {
    }

    public RuleAttribute(string pattern, string errorMessage = "")
    {
        Pattern = pattern;
        ErrorMessage = errorMessage;
    }

    /// <summary>
    /// 字段格式验证
    /// </summary>
    /// <returns></returns>
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        var stringValue = value?.ToString();
        //验证字段是否为空
        if (string.IsNullOrWhiteSpace(stringValue))
        {
            return new ValidationResult("参数输入格式不正确！");
        }
        //验证表达式是否为空
        if (string.IsNullOrWhiteSpace(Pattern))
        {
            return new ValidationResult("字段验证表达式为空！");
        }
        //验证是否符合表达式
        if (!Regex.IsMatch(stringValue, Pattern))
        {
            if (string.IsNullOrWhiteSpace(ErrorMessage))
            {
                ErrorMessage = "参数输入格式不正确！";
            }
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}